package bio.mytomcat;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author LuZhouJin
 * @Date 2023/8/4
 */
public class MyTomcat {
    private int port = 8080;
    private ServerSocket server;
    private Map<String, MyServlet> servletMapping = new HashMap<>();
    private Properties webxml = new Properties();

    private void init() {
        try {
            //加载web.xml 这里使用mytomcat.properties替代
            String WEB_INF = this.getClass().getResource("/").getPath();
            FileInputStream fis = new FileInputStream(WEB_INF + "mytomcat.properties");

            webxml.load(fis);

            for (Object k : webxml.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String servletName = key.replaceAll("\\.url$", "");
                    String url = webxml.getProperty(key);
                    String className = webxml.getProperty(servletName + ".className");
                    //单实例，多线程
                    MyServlet o = (MyServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //加载配置忘记，初始化 servletMapping
        init();
        
        try {
            server = new ServerSocket(this.port);

            System.out.println("MyTomcat 已启动，监听端口："+this.port);
            
            //等待用户请求
            while (true){
                Socket client = server.accept();
                //HTTP请求，收到的就是字符串
                process(client);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket client) throws Exception {
        InputStream is = client.getInputStream();
        OutputStream os = client.getOutputStream();

        MyRequest request = new MyRequest(is);
        MyResponse response = new MyResponse(os);

        //从协议中获取url
        String url = request.getUrl();
        if (servletMapping.containsKey(url)){
            servletMapping.get(url).service(request,response);
        }else {
            response.write("404 - Not Found");
        }

        os.flush();
        os.close();

        is.close();
        client.close();
    }

    public static void main(String[] args) {
        new MyTomcat().start();
    }

}
